package com.xiaoyu.studyworkspace.common.util;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.xiaoyu.studyworkspace.common.kapaentity.register.appbooting.AppBooting;
import com.xiaoyu.studyworkspace.common.kapaentity.register.proxy.ProxyAuthenticator;
import com.xiaoyu.studyworkspace.common.kapaentity.register.proxy.ProxyBean;
import com.xiaoyu.studyworkspace.common.kapaentity.register.registerbean.RegisterBean;
import com.xiaoyu.studyworkspace.common.kapaentity.scan.TenXun;
import com.xiaoyu.studyworkspace.common.kapaentity.userinfo.RootBean;
import com.xiaoyu.studyworkspace.common.kapaentity.websocket.KapaCode;

import java.net.Authenticator;
import java.util.*;

public class KapaHttpUtil {

    // 用户名密码认证(动态代理/独享代理)
    private final static String ProxyUser = "17576815442";
    private final static String ProxyPass = "zhenfu007";
    private final static String proxyURL = "http://v2.api.juliangip.com/unlimited/getips?auto_white=1&num=1&pt=1&result_type=json&trade_no=5058085814107839&sign=07bc43b1cebb9f101a9f168beb55c0ac";

    //http://8.138.56.30:8877/captcha/tx?aid=193773642&ip=
    private final static String tx = "http://8.138.56.30:8877/captcha/tx?aid=193773642&ip=";

    private KapaHttpUtil() {
    }


    public static String convertParam(Map<String, Object> paramMap) {
        if (MapUtil.isEmpty(paramMap)) {
            //为空则返回null
            return null;
        }
        String body = "";
        int sum = 0;
        for (String key : paramMap.keySet()) {
            sum++;
            body = body + key + "=" + paramMap.get(key);
            if (sum <= paramMap.keySet().size() - 1) {
                body += "&";
            }
        }
        return body;
    }


    public static RegisterBean getRegisterBean(HashMap<String, Object> paramMap) {
        int sum = 0;
        while (true) {

            sum++;
            // 代理IP、端口号
            //获取代理ip
            String proxyInfo = HttpUtil.get(proxyURL);
            ProxyBean proxyBean = JSONUtil.toBean(proxyInfo, ProxyBean.class);
            // 目标网站
            String url = KapaCode.URL;
            // JDK 8u111版本后，目标页面为HTTPS协议，启用proxy用户密码鉴权
            System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");
            // 设置请求验证信息
            Authenticator.setDefault(new ProxyAuthenticator(ProxyUser, ProxyPass));
            // 发送请求
            String proxyAndPort = proxyBean.getData().getProxy_list().get(0);
            System.out.println(proxyAndPort);
            String ProxyHost = proxyAndPort.substring(0, proxyAndPort.lastIndexOf(":"));
            int ProxyPort = Integer.parseInt(proxyAndPort.substring((proxyAndPort.lastIndexOf(":") + 1)));
            try {
                HttpResponse result = HttpRequest.post(url)
                        .setHttpProxy(ProxyHost, ProxyPort)
                        .body(KapaHttpUtil.convertParam(paramMap))
                        .timeout(20000)//设置超时，毫秒
                        .execute();
                String body = result.body();
                System.out.println(body);
                RegisterBean registerBean = JSONUtil.toBean(body, RegisterBean.class);
                return registerBean;
            } catch (Exception e) {
                if (sum > 10) {
                    return null;
                }
                System.out.println("出错重新抓ip,获取出错消息：" + e.getMessage());
            }
        }

    }

    public static RootBean getRootBean(HashMap<String, Object> paramMap) {

        int sum = 0;
        while (true) {
            sum++;
            // 代理IP、端口号
            //获取代理ip
            String proxyInfo = HttpUtil.get(proxyURL);
            ProxyBean proxyBean = JSONUtil.toBean(proxyInfo, ProxyBean.class);
            // 目标网站
            String url = KapaCode.URL;
            // JDK 8u111版本后，目标页面为HTTPS协议，启用proxy用户密码鉴权
            System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");
            // 设置请求验证信息
            Authenticator.setDefault(new ProxyAuthenticator(ProxyUser, ProxyPass));
            // 发送请求
            String proxyAndPort = proxyBean.getData().getProxy_list().get(0);
            System.out.println(proxyAndPort);

            String ProxyHost = proxyAndPort.substring(0, proxyAndPort.lastIndexOf(":"));
            int ProxyPort = Integer.parseInt(proxyAndPort.substring((proxyAndPort.lastIndexOf(":") + 1)));
            try {
                HttpResponse result = HttpRequest.post(url)
                        .setHttpProxy(ProxyHost, ProxyPort)
                        .body(KapaHttpUtil.convertParam(paramMap))
                        .timeout(20000)//设置超时，毫秒
                        .execute();
                String body = result.body();
                System.out.println(body);
                RootBean rootBean = JSONUtil.toBean(body, RootBean.class);
                return rootBean;
            } catch (Exception e) {
                if (sum > 10) {
                    return null;
                }
                System.out.println("出错重新抓ip,获取出错消息：" + e.getMessage());
            }
        }

    }

    /**
     * 需要重试，调用api获取滑块密钥,失败重试
     */
    public static TenXun getTxTicket() {
        int sum = 0;
        while (true) {
            sum++;
            // 代理IP、端口号
            //获取代理ip
            String proxyInfo = HttpUtil.get(proxyURL);
            ProxyBean proxyBean = JSONUtil.toBean(proxyInfo, ProxyBean.class);
            // 目标网站
            // JDK 8u111版本后，目标页面为HTTPS协议，启用proxy用户密码鉴权
            System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");
            // 设置请求验证信息
            Authenticator.setDefault(new ProxyAuthenticator(ProxyUser, ProxyPass));
            // 发送请求
            String proxyAndPort = proxyBean.getData().getProxy_list().get(0);
            try {
                HttpResponse result = HttpRequest.get(tx + proxyAndPort)
                        .timeout(20000)//设置超时，毫秒
                        .execute();
                String txTicket = result.body();
                System.out.println(txTicket);
                TenXun tenXun = JSONUtil.toBean(txTicket, TenXun.class);
                if (StrUtil.isNotEmpty(tenXun.getResult().getTicket())) {
                    //成功
                    return tenXun;
                }
            } catch (Exception e) {
                //失败
                if (sum > 10) {
                    return null;
                }
                System.out.println("出错重新抓ip,获取出错消息：" + e.getMessage());
            }
        }
    }

    public static AppBooting getAppBooting() {
        int sum = 0;
        while (true) {
            sum++;
            // 代理IP、端口号
            //获取代理ip
            String proxyInfo = HttpUtil.get(proxyURL);
            System.out.println(proxyInfo);
            ProxyBean proxyBean = JSONUtil.toBean(proxyInfo, ProxyBean.class);
            // 目标网站
            String url = KapaCode.URL_APPBOOTING;
            HashMap<String, Object> paramMap = new HashMap<>();
            paramMap.put(KapaParam.DEPLOY_APP_ID, KapaCode.DEPLOY_APP_ID);
            // JDK 8u111版本后，目标页面为HTTPS协议，启用proxy用户密码鉴权
            System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");
            // 设置请求验证信息
            Authenticator.setDefault(new ProxyAuthenticator(ProxyUser, ProxyPass));
            // 发送请求
            String proxyAndPort = proxyBean.getData().getProxy_list().get(0);
            System.out.println(proxyAndPort);
            String ProxyHost = proxyAndPort.substring(0, proxyAndPort.lastIndexOf(":"));
            int ProxyPort = Integer.parseInt(proxyAndPort.substring((proxyAndPort.lastIndexOf(":") + 1)));
            try {
                HttpResponse result = HttpRequest.post(url)
                        .setHttpProxy(ProxyHost, ProxyPort)
                        .body(KapaHttpUtil.convertParam(paramMap))
                        .timeout(20000)//设置超时，毫秒
                        .execute();
                String body = result.body();
                AppBooting appBooting = JSONUtil.toBean(body, AppBooting.class);
                if (appBooting.getError() == null) {
                    //成功
                    return appBooting;
                }
            } catch (Exception e) {
                //失败
                if (sum > 10) {
                    return null;
                }
                System.out.println("出错重新抓ip,获取出错消息：" + e.getMessage());
            }
        }
    }


}
